<template>
  <div class="book-recommend">
    <!-- 轮播区 -->
    <section class="banner-area">
      <el-carousel
        height="450px"
        indicator-position="outside"
        arrow="always"
        :interval="5000"
      >
        <el-carousel-item
          v-for="item in carousel"
          :key="item.carousel_id"
          @click.native="handleBannerClick(item)"
        >
          <div class="banner-item">
            <img
              :src="$target + item.imgPath"
              :alt="item.describes"
              class="banner-image"
            />
            <div class="banner-text">
              <h3>{{ item.describes }}</h3>
              <p class="banner-subtitle">{{ getBannerSubtitle(item) }}</p>
              <el-button
                type="primary"
                round
                size="medium"
                @click.stop="handleBannerClick(item)"
              >
                立即探索 <i class="el-icon-arrow-right"></i>
              </el-button>
            </div>
          </div>
        </el-carousel-item>
      </el-carousel>
    </section>

    <!-- 主内容区 -->
    <main class="main-content">
      <!-- 个性化推荐 -->
      <section class="recommend-area">
        <div class="section-header">
          <div class="section-title">
            <i class="el-icon-collection"></i>
            <span>个性化推荐</span>
            <el-tag type="info" effect="dark" size="small">AI智能推荐</el-tag>
          </div>
          <el-button
            type="text"
            class="refresh-btn"
            @click="refreshRecommendations"
          >
            <i class="el-icon-refresh"></i> 换一批
          </el-button>
        </div>
        <div class="section-subtitle">根据您的阅读偏好精心挑选</div>
        <div v-loading="loading.snackList" class="book-list">
          <div
            class="book-item"
            v-for="item in snackList"
            :key="item.product_id"
            @click="goToDetail(item.product_id)"
          >
            <div class="book-cover">
              <img
                :src="$target + item.product_picture"
                :alt="item.product_name"
              />
              <div class="book-tags">
                <span class="tag-recommend">推荐</span>
                <span
                  class="tag-discount"
                  v-if="item.product_selling_price < item.product_price"
                >
                  特惠 {{ calculateDiscount(item) }}%
                </span>
              </div>
            </div>
            <div class="book-info">
              <h4>{{ item.product_name }}</h4>
              <p class="book-desc">{{ item.product_title || "暂无描述" }}</p>
              <div class="book-footer">
                <div class="rating-container">
                  <el-rate
                    v-model="item.rating"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value}"
                  >
                  </el-rate>
                  <span class="sales-count"
                    >已售 {{ item.actual_sales || 0 }}</span
                  >
                </div>
                <div class="price-box">
                  <span class="current-price"
                    >¥{{ item.product_selling_price }}</span
                  >
                  <span
                    class="original-price"
                    v-if="item.product_selling_price < item.product_price"
                  >
                    ¥{{ item.product_price }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 新书速递 -->
      <section class="new-book-area">
        <div class="section-header">
          <div class="section-title">
            <i class="el-icon-star-on"></i>
            <span>新书速递</span>
            <el-tag type="success" effect="dark" size="small">每日更新</el-tag>
          </div>
          <router-link to="/books/new" class="more-link">
            查看更多新书 <i class="el-icon-arrow-right"></i>
          </router-link>
        </div>
        <div class="section-subtitle">最新上架优质图书</div>
        <div v-loading="loading.makeupList" class="new-book-scroll">
          <div
            class="new-book-item"
            v-for="item in shuffledMakeupList"
            :key="item.product_id"
            @click="goToDetail(item.product_id)"
          >
            <div class="new-book-card">
              <img
                :src="$target + item.product_picture"
                :alt="item.product_name"
              />
              <div class="new-badge">NEW</div>
              <h4>{{ item.product_name }}</h4>
              <p class="book-intro">{{ item.product_title || "暂无描述" }}</p>
              <div class="price-container">
                <span class="price">¥{{ item.product_selling_price }}</span>
                <span
                  class="original-price"
                  v-if="item.product_selling_price < item.product_price"
                >
                  ¥{{ item.product_price }}
                </span>
              </div>
            </div>
          </div>
        </div>
      </section>

      <!-- 热门榜单 -->
      <section class="ranking-area">
        <div class="section-header">
          <div class="section-title">
            <i class="el-icon-trophy"></i>
            <span>热门榜单</span>
            <el-tag type="danger" effect="dark" size="small">实时更新</el-tag>
          </div>
          <el-select
            v-model="rankingPeriod"
            size="mini"
            @change="changeRankingPeriod"
          >
            <el-option
              v-for="item in rankingOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </div>
        <div class="section-subtitle">本周最受读者欢迎的图书</div>
        <div v-loading="loading.apparelList" class="ranking-list">
          <div
            class="ranking-item"
            v-for="(item, index) in apparelList"
            :key="item.product_id"
            @click="goToDetail(item.product_id)"
          >
            <div class="rank-number" :class="'rank-' + (index + 1)">
              {{ index + 1 }}
            </div>
            <img
              :src="$target + item.product_picture"
              class="book-img"
              :alt="item.product_name"
            />
            <div class="book-details">
              <h4>{{ item.product_name }}</h4>
              <p>{{ item.product_title || "暂无描述" }}</p>
              <div class="rank-footer">
                <el-rate v-model="item.rating" disabled class="small-rate">
                </el-rate>
                <span class="sales-count"
                  >销量 {{ item.actual_sales || 0 }}</span
                >
              </div>
            </div>
            <el-button
              type="text"
              class="detail-btn"
              @click.stop="goToDetail(item.product_id)"
            >
              查看详情 <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
        </div>
      </section>
    </main>
  </div>
</template>

<script>
export default {
  data() {
    return {
      carousel: [],
      snackList: [], // 个性化推荐
      makeupList: [], // 新书速递
      apparelList: [], // 热门榜单
      loading: {
        snackList: false,
        makeupList: false,
        apparelList: false,
      },
      rankingPeriod: "week",
      rankingOptions: [
        { value: "day", label: "今日" },
        { value: "week", label: "本周" },
        { value: "month", label: "本月" },
      ],
      bannerSubtitles: [
        "探索知识的海洋，发现你的下一本最爱",
        "精选优质图书，满足你的阅读渴望",
        "限时特惠，不容错过的阅读盛宴",
      ],
    };
  },
  created() {
    this.getCarouselData();
    this.getProductData();
  },
  computed: {
    shuffledMakeupList() {
      // 复制原数组避免修改原始数据
      const array = [...this.makeupList];
      // Fisher-Yates 洗牌算法
      for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
      }
      return array;
    },
  },
  methods: {
    getCarouselData() {
      this.$axios
        .post("/api/resources/carousel", {})
        .then((res) => {
          this.carousel = res.data.carousel;
        })
        .catch((err) => {
          console.error("获取轮播图失败:", err);
          this.$message.error("获取轮播图数据失败");
        });
    },

    getProductData() {
      this.getPersonalizedRecommendation();
      this.getNewArrivals();
      this.getPopularBooks();
    },

    getPersonalizedRecommendation() {
      this.loading.snackList = true;
      this.$axios
        .post("/api/product/getPersonalizedRecommendations", {
          limit: 8,
          algorithm: "random",
        })
        .then((res) => {
          if (res.data.code === "001") {
            this.snackList = res.data.recommendations.map((item) => ({
              ...item,
              rating: (Math.random() * 2 + 3).toFixed(1),
            }));
          }
        })
        .catch((err) => {
          console.error("获取个性化推荐失败:", err);
          this.$message.error("获取推荐数据失败");
        })
        .finally(() => {
          this.loading.snackList = false;
        });
    },

    getNewArrivals() {
      this.loading.makeupList = true;
      this.$axios
        .post("/api/product/getPersonalizedRecommendations", {
          limit: 10,
          algorithm: "new-arrivals",
        })
        .then((res) => {
          if (res.data.code === "001") {
            this.makeupList = res.data.recommendations;
          }
        })
        .catch((err) => {
          console.error("获取新书速递失败:", err);
        })
        .finally(() => {
          this.loading.makeupList = false;
        });
    },

    getPopularBooks() {
      this.loading.apparelList = true;
      this.$axios
        .post("/api/product/getPersonalizedRecommendations", {
          limit: 10,
          algorithm: "popular",
        })
        .then((res) => {
          if (res.data.code === "001") {
            this.apparelList = res.data.recommendations;
          }
        })
        .catch((err) => {
          console.error("获取热门榜单失败:", err);
        })
        .finally(() => {
          this.loading.apparelList = false;
        });
    },

    refreshRecommendations() {
      this.getPersonalizedRecommendation();
      this.$message.success("已为您刷新推荐内容");
    },

    changeRankingPeriod() {
      this.getPopularBooks();
    },

    calculateDiscount(item) {
      if (
        !item.product_price ||
        item.product_price <= item.product_selling_price
      ) {
        return 0;
      }
      return Math.round(
        (1 - item.product_selling_price / item.product_price) * 100
      );
    },

    getBannerSubtitle(item) {
      return this.bannerSubtitles[
        this.carousel.indexOf(item) % this.bannerSubtitles.length
      ];
    },

    handleBannerClick(item) {
      this.$router.push(
        `/search?keyword=${encodeURIComponent(item.describes)}`
      );
    },

    goToDetail(productId) {
      this.$router.push(`/goods/details?productID=${productId}`);
    },
  },
};
</script>

<style>
/* 基础样式 */
.book-recommend {
  font-family: "PingFang SC", "Microsoft YaHei", sans-serif;
  background-color: #f8f9fa;
  color: #333;
  padding-bottom: 40px;
}

/* 轮播区样式 */
.banner-area {
  margin-bottom: 50px;
}

.banner-area .el-carousel {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
}

.banner-area .el-carousel__arrow {
  background-color: rgba(255, 255, 255, 0.3);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
}

.banner-area .el-carousel__arrow:hover {
  background-color: rgba(255, 255, 255, 0.5);
}

.banner-area .el-carousel__indicators {
  bottom: 20px;
}

.banner-item {
  position: relative;
  height: 450px;
}

.banner-item .banner-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 5s ease;
}

.banner-item:hover .banner-image {
  transform: scale(1.05);
}

.banner-text {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 40px;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  color: white;
  text-align: center;
}

.banner-text h3 {
  font-size: 2.2rem;
  margin-bottom: 12px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  font-weight: 600;
}

.banner-text .banner-subtitle {
  font-size: 1.1rem;
  margin-bottom: 20px;
  opacity: 0.9;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.banner-text .el-button {
  font-size: 1rem;
  padding: 12px 32px;
  background: #4361ee;
  border: none;
  font-weight: 600;
  transition: all 0.3s ease;
}

.banner-text .el-button:hover {
  background: #3a56d4;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(67, 97, 238, 0.3);
}

.banner-text .el-button i {
  margin-left: 6px;
}

/* 主内容区 */
.main-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 区块标题样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.section-title {
  display: flex;
  align-items: center;
  font-size: 1.5rem;
  font-weight: 600;
}

.section-title i {
  margin-right: 12px;
  font-size: 1.8rem;
  color: #4361ee;
}

.section-title .el-tag {
  margin-left: 12px;
  height: 24px;
  line-height: 22px;
  font-weight: 600;
}

.section-subtitle {
  font-size: 1rem;
  color: #666;
  margin-bottom: 24px;
}

.refresh-btn {
  color: #666;
  font-size: 0.9rem;
}

.refresh-btn:hover {
  color: #4361ee;
}

.refresh-btn i {
  margin-right: 4px;
}

.more-link {
  color: #666;
  font-size: 0.9rem;
  text-decoration: none;
  display: flex;
  align-items: center;
}

.more-link:hover {
  color: #4361ee;
}

.more-link i {
  margin-left: 4px;
  font-size: 0.8rem;
}

/* 图书列表样式 */
.book-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
  min-height: 400px;
}

.book-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.book-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 28px rgba(0, 0, 0, 0.12);
}

.book-cover {
  position: relative;
  height: 280px;
  overflow: hidden;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.book-item:hover .book-cover img {
  transform: scale(1.05);
}

.book-tags {
  position: absolute;
  top: 16px;
  left: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.book-tags span {
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.75rem;
  font-weight: 600;
}

.book-tags .tag-recommend {
  background: #4361ee;
  color: white;
}

.book-tags .tag-discount {
  background: #ff4757;
  color: white;
}

.book-info {
  padding: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.book-info h4 {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-info .book-desc {
  font-size: 0.875rem;
  color: #666;
  margin: 0 0 16px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.4;
  flex: 1;
}

.book-footer {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.rating-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.rating-container .sales-count {
  font-size: 0.75rem;
  color: #999;
}

.price-box {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-box .current-price {
  font-size: 1.25rem;
  font-weight: 700;
  color: #ff4757;
}

.price-box .original-price {
  font-size: 0.875rem;
  color: #999;
  text-decoration: line-through;
}

/* 新书速递区域 */
.new-book-scroll {
  display: flex;
  overflow-x: auto;
  padding: 16px 8px;
  gap: 20px;
  margin-bottom: 40px;
  scrollbar-width: thin;
  scrollbar-color: #4361ee transparent;
  min-height: 320px;
}

.new-book-scroll::-webkit-scrollbar {
  height: 6px;
}

.new-book-scroll::-webkit-scrollbar-thumb {
  background-color: #4361ee;
  border-radius: 3px;
}

.new-book-scroll::-webkit-scrollbar-track {
  background: transparent;
}

.new-book-item {
  flex: 0 0 200px;
  cursor: pointer;
}

.new-book-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  height: 100%;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  position: relative;
  display: flex;
  flex-direction: column;
}

.new-book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
}

.new-book-card img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 8px;
  margin-bottom: 16px;
}

.new-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #00b894;
  color: white;
  padding: 4px 10px;
  border-radius: 20px;
  font-size: 0.75rem;
  font-weight: 600;
}

.new-book-card h4 {
  font-size: 1rem;
  font-weight: 600;
  margin: 0 0 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-intro {
  font-size: 0.8125rem;
  color: #666;
  margin: 0 0 12px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-height: 1.4;
  flex: 1;
}

.price-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.price-container .price {
  font-size: 1.125rem;
  font-weight: 700;
  color: #4361ee;
}

.price-container .original-price {
  font-size: 0.8125rem;
  color: #999;
  text-decoration: line-through;
}

/* 排行榜区域 */
.ranking-list {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
  margin-bottom: 60px;
  min-height: 500px;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 20px;
  transition: all 0.3s ease;
  cursor: pointer;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.ranking-item:last-child {
  border-bottom: none;
}

.ranking-item:hover {
  background: rgba(67, 97, 238, 0.03);
}

.rank-number {
  width: 32px;
  height: 32px;
  line-height: 32px;
  text-align: center;
  background: #f0f0f0;
  border-radius: 50%;
  margin-right: 20px;
  font-size: 0.875rem;
  font-weight: 700;
  color: #666;
  transition: all 0.3s ease;
}

.rank-number.rank-1 {
  background: #ff4757 !important;
  color: white !important;
}

.rank-number.rank-2 {
  background: #ffa502 !important;
  color: white !important;
}

.rank-number.rank-3 {
  background: #4361ee !important;
  color: white !important;
}

.ranking-item:hover .rank-number {
  transform: scale(1.1);
}

.book-img {
  width: 60px;
  height: 80px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 20px;
}

.book-details {
  flex: 1;
}

.book-details h4 {
  font-size: 1rem;
  font-weight: 600;
  margin: 0 0 4px;
}

.book-details p {
  font-size: 0.8125rem;
  color: #666;
  margin: 0 0 8px;
}

.rank-footer {
  display: flex;
  align-items: center;
  margin-top: 8px;
}

.rank-footer .small-rate {
  margin-right: 10px;
}

.rank-footer .small-rate .el-rate__icon {
  font-size: 14px;
}

.rank-footer .sales-count {
  font-size: 0.75rem;
  color: #999;
}

.detail-btn {
  padding: 0;
  font-size: 0.8125rem;
  color: #4361ee;
  font-weight: 600;
}

.detail-btn:hover {
  color: #3a56d4;
}

.detail-btn i {
  margin-left: 4px;
  font-size: 0.8rem;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .banner-text h3 {
    font-size: 2rem;
  }

  .book-list {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 20px;
  }

  .new-book-item {
    flex: 0 0 180px;
  }
}

@media (max-width: 768px) {
  .banner-area {
    margin-bottom: 30px;
  }

  .banner-item {
    height: 360px;
  }

  .banner-text {
    padding: 24px;
  }

  .banner-text h3 {
    font-size: 1.5rem;
  }

  .banner-text .banner-subtitle {
    font-size: 1rem;
  }

  .main-content {
    padding: 0 16px;
  }

  .section-title {
    font-size: 1.25rem;
  }

  .section-title i {
    font-size: 1.5rem;
  }

  .book-list {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 16px;
  }

  .book-cover {
    height: 200px;
  }

  .ranking-item {
    padding: 16px;
  }

  .rank-number {
    margin-right: 12px;
  }
}

@media (max-width: 480px) {
  .banner-item {
    height: 280px;
  }

  .banner-text {
    padding: 16px;
  }

  .banner-text h3 {
    font-size: 1.25rem;
    margin-bottom: 8px;
  }

  .banner-text .banner-subtitle {
    font-size: 0.875rem;
    margin-bottom: 12px;
  }

  .banner-text .el-button {
    padding: 10px 24px;
    font-size: 0.875rem;
  }

  .book-list {
    grid-template-columns: repeat(2, 1fr);
  }

  .new-book-item {
    flex: 0 0 150px;
  }

  .ranking-item {
    flex-direction: column;
    align-items: flex-start;
    padding: 12px;
  }

  .rank-number {
    margin-bottom: 12px;
    margin-right: 0;
  }

  .book-img {
    margin-bottom: 12px;
    margin-right: 0;
    width: 100%;
    height: 120px;
  }

  .detail-btn {
    align-self: flex-end;
    margin-top: 8px;
  }
}
</style>
